package cn.wolfcode.ssm.service.impl;

import cn.wolfcode.ssm.domain.Department;
import cn.wolfcode.ssm.domain.Employee;
import cn.wolfcode.ssm.exception.LogicException;
import cn.wolfcode.ssm.mapper.DepartmentMapper;
import cn.wolfcode.ssm.mapper.EmployeeMapper;
import cn.wolfcode.ssm.qo.EmployeeQueryObject;
import cn.wolfcode.ssm.service.IEmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
@Transactional
@Service
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private DepartmentMapper departmentMapper;


    @Override
    public void deleteById(Long id) {
        employeeMapper.deleteRelationById(id);
        if(id != null){
            employeeMapper.deleteByPrimaryKey(id);
        }
    }

    @Override
    public void save(Employee employee,Long[] ids) {
        if(ids!=null){
            employeeMapper.insertRelation(employee.getId(),ids);
        }
        employeeMapper.insert(employee);

    }

    @Override
    public Employee selectById(Long id) {
        if(id != null){
            return employeeMapper.selectByPrimaryKey(id);
        }
        return null;
    }



    @Override
    public void updateById(Employee employee,Long[] ids) {
        //先删除关系
        employeeMapper.deleteRelationById(employee.getId());
        //再添加关系
        if(ids != null && ids.length>0){
            employeeMapper.insertRelation(employee.getId(),ids);
            employeeMapper.updateByPrimaryKey(employee);
        }

    }

    @Override
    public List<Employee> listAll() {
        return employeeMapper.ListAll();
    }

    @Override
    public PageInfo<Employee> query(EmployeeQueryObject qo) {
        //开始分页
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        //拦截对应的sql，加上LIMIT字句
        List<Employee> employees = employeeMapper.selectForList(qo);
        //自动封装（只需要提供List参数）
        return new PageInfo<>(employees);


    }

    @Override
    public Employee login(String username, String password) {

        //判断账号是否为空
        if(!StringUtils.hasText(username)){
            throw new LogicException("账号不能为空");
        }
        //判断密码是否空
        if(!StringUtils.hasText(password)){
            throw new LogicException("密码不能为空");
        }

        Employee employee = employeeMapper.selectByUsernameAndPassword(username, password);
        if(employee == null){
            throw new LogicException("账号密码错误");
        }else {
            if (employee.isStatus()){
                return employee;
            }
            throw new LogicException("无权限");

        }
    }

    @Override
    public Employee checkUsername(String username) {
        return employeeMapper.selectByUsername(username);
    }

    @Override
    public Workbook exportXls(EmployeeQueryObject qo) {
        //创建Excel对象HSSFWorkbook对象
        Workbook wb = new HSSFWorkbook();
        //创建Excel表
        Sheet sheet = wb.createSheet();
        Row row = sheet.createRow(0);
        row.createCell(0).setCellValue("用户名");
        row.createCell(1).setCellValue("名字");
        row.createCell(2).setCellValue("邮箱");
        row.createCell(3).setCellValue("年龄");
        row.createCell(4).setCellValue("部门");
        List<Employee> employees = employeeMapper.selectForList(qo);
        for (int i = 0; i < employees.size() ; i++) {
            Row eleRow = sheet.createRow(i+1);
            Employee employee = employees.get(i);
            eleRow.createCell(0).setCellValue(employee.getUsername());
            eleRow.createCell(1).setCellValue(employee.getName());
            eleRow.createCell(2).setCellValue(employee.getEmail());
            eleRow.createCell(3).setCellValue(employee.getAge());
            eleRow.createCell(4).setCellValue(employee.getDepartment().getName());
        }
        return wb;
    }

    @Override
    public String importXls(MultipartFile file, String password) throws IOException {
        //
        //List<String> exMessages = new ArrayList<>();
        //使用POI操作file文件,将file文件写到wb中
        Workbook wb = new HSSFWorkbook(file.getInputStream());
        //读取第一页
        Sheet sheet = wb.getSheetAt(0);
        //获取最后一行的索引
        int lastRowNum = sheet.getLastRowNum();
        //循环遍历
        for (int i = 0; i <= lastRowNum ; i++) {
            try {
                Employee employee = new Employee();
                Cell cell = sheet.getRow(i + 1).getCell(0);
                if(cell == null){
                    throw new LogicException("用户名不能为空");
                }
                if (cell.getCellType()!= CellType.STRING) {
                    throw new LogicException("用户名只能为中文或英文");
                }
                employee.setName(cell.getStringCellValue());//username
                //判断用户名是否存在
                String username = sheet.getRow(i + 1).getCell(1).getStringCellValue();
                if(employeeMapper.selectByUsername(username) != null){
                    throw new RuntimeException("第"+i+1+"行的"+username+"用户名已经存在");
                }
                employee.setPassword(password);//password
                employee.setUsername(username);//username
                employee.setEmail(sheet.getRow(i+1).getCell(2).getStringCellValue());//email
                employee.setAge((int)sheet.getRow(i+1).getCell(3).getNumericCellValue());//age
                String deptName = sheet.getRow(i + 1).getCell(4).getStringCellValue();
                //根据部门名字后去部门id
                Department department = departmentMapper.selectByName(deptName);
                employee.setDeptId(department.getId());//deptId
                employeeMapper.insert(employee);
            } catch (LogicException e) {
                e.printStackTrace();
                return e.getMessage();
            }
        }
        return null;
    }

    @Override
    public void updateForStatus (Long id) {
        if(id != null){
            Employee employee = employeeMapper.selectByPrimaryKey(id);
            employee.setStatus(!employee.isStatus());
            employeeMapper.updateByPrimaryKey(employee);
        }
    }
}
